package com.github.cyf.upload.controller;

import com.github.cyf.common.exception.BizException;
import com.github.cyf.common.model.Result;
import com.github.cyf.upload.entity.dto.FileUploadDTO;
import com.github.cyf.upload.local.LocalDownload;
import com.github.cyf.upload.local.pojo.UploadFileParam;
import com.github.cyf.upload.local.pojo.UploadProgress;
import com.github.cyf.upload.properties.UploadProperties;
import com.github.cyf.upload.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @author chenyifan
 * @create 2025-05-22 15:52
 */
@Controller
@RequestMapping(value="/")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private UploadProperties uploadProperties;

    @PostMapping(value = "checkMd5")
    @ResponseBody
    public Result<Boolean> checkFileMd5(String md5) {
        return new Result<Boolean>().setData(fileService.checkMd5(md5));
    }

    @PostMapping(value = "getUploadProgress")
    @ResponseBody
    public Result<UploadProgress> upload(String md5, String name) {
        return new Result<UploadProgress>().setData(fileService.getUploadProgress(md5, name));
    }

    @PostMapping("/download")
    public void download(String path) {
        try {
            LocalDownload.downloadFile(Paths.get(uploadProperties.getSaveDir(), path).toString(), request, response);
        } catch (FileNotFoundException e) {
            log.error("download error");
            throw new BizException("文件下载失败");
        }
    }

}
